class Solution {
public:
    struct cmpFrqnt
    {
        bool operator()(const pair<string, int>& p1, const pair<string, int>& p2)
        {
            return p1.second > p2.second || (p1.second == p2.second && p1.first < p2.first);
        }
    };
    vector<string> topKFrequent(vector<string>& words, int k) {
        map<string, int> index;
        for (auto& str : words)
        {
            index[str]++;
        }

        vector<pair<string, int>> vt(index.begin(), index.end());
        sort(vt.begin(), vt.end(), cmpFrqnt());

        vector<string> ans;
        for (size_t i = 0; i < k; ++i)
        {
            ans.push_back(vt[i].first);
        }
        return ans;
    }
};